import { Button, Drawer, DrawerProps, Form, Input, Select, Spin } from "antd";
import { memo, useEffect, useImperativeHandle, useRef } from "react"
import { IArticle, useAddArticle, useUpdateArticle } from "../../../service/article-service";
import { useForm } from "antd/es/form/Form";
import { IEditRef, IFormRef, IPage } from "../../../types";
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from "react-query";
import { IUploadImgRefHandler, UploadImage } from "../../../components/upload-img";
import RichEdit from "../../../components/edit"

type IArticleParams = {
    article?: IArticle;
    open: boolean;
    onRef: React.MutableRefObject<IFormRef | undefined>;
    openFn: (open: boolean) => void;
    refetch: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<IArticle>, unknown>>
} & DrawerProps

const ArticleForm = ({ article, open, onRef, openFn, refetch, ...props }: IArticleParams) => {

    const [form] = useForm();
    const imageRef = useRef<IUploadImgRefHandler>();
    const richEditRef = useRef<IEditRef>()

    useEffect(() => {
        if (article) {
            form.setFieldsValue({
                articleId: article.articleId,
                articleTitle: article.articleTitle,
                articleBanner: article.articleBanner,
                recommend: article.recommend,
                unitName: article.unitName,
                watchTime: article.watchTime,
            });
            imageRef.current?.fill([article.articleBanner])
        }
    }, [article])


    /**
  * 更新方法
  */
    const updateHandler = async () => {
        const values = await form.getFieldsValue();
        await updateMutation({ articleId: article?.articleId, ...values });
        refetch();
        openFn(false);
        form.resetFields();
    }

    /**
     * 保存方法
     */
    const saveHandler = async () => {
        form.setFieldValue("articleText", JSON.stringify(richEditRef.current?.getData()))
        const isPass = await form.validateFields();
        if (!isPass) {
            return
        }
        const values = form.getFieldsValue();
        await addMutation({ ...values });
        refetch();
        openFn(false);
        form.resetFields();
    }
    /**
      * 上传头像回调
      * @param url
      */
    const getUrlHandler = (url: string) => {
        form.setFieldValue("articleBanner", url)
    };
    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(onRef, () => ({
        reset: () => {
            form.resetFields();
        },
        save: () => {
            saveHandler();
        },
        update: async () => {
            updateHandler();
        }
    }));

    /**
   * !添加hook
   */
    const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddArticle();
    /**
     *!修改hook
     */
    const { mutateAsync: updateMutation, isLoading: UIsLoading } = useUpdateArticle();
    return <Drawer title={'新闻编辑'} placement="right" width={'60rem'} closable={true} onClose={() => openFn(false)} forceRender={true} open={open} footer={
        <>
            {
                article ? (
                    <Button onClick={() => { updateHandler(); }}>
                        修改
                    </Button>
                ) : (
                    <Button onClick={() => { saveHandler(); }}>
                        保存
                    </Button>
                )
            }
        </>
    }>
        <Spin spinning={addIsLoading || UIsLoading}>
            <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                <Form.Item label={'文章标题'} name={'articleTitle'} rules={[{ required: true, message: '文章标题不能为空' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label={'文章标题图片'} name={'articleBanner'} rules={[{ required: true, message: '文章标题图片不能为空' }]}>
                    <UploadImage getUrlHandler={getUrlHandler} maxCount={1} onRef={imageRef} />
                </Form.Item>
                <Form.Item label={'发布单位'} name={'unitName'} rules={[{ required: true, message: '发布单位不能为空' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label={'是否推荐'} name={'recommend'} rules={[{ required: true, message: '是否推荐不能为空' }]}>
                    <Select
                        options={[
                            { value: 1, label: '是' },
                            { value: 2, label: '否' },
                        ]}
                    />
                </Form.Item>
                <Form.Item label={'文章内容'} name={'articleText'} rules={[{ required: true, message: '文章内容不能为空' }]}>
                    <RichEdit content={article?.articleText || '123'} onRef={richEditRef} />
                </Form.Item>
            </Form>
        </Spin>
    </Drawer>
}


export default memo(ArticleForm)